/*
 * Commu.c
 *
 *  Created on: 2025-4-30
 *      Author: Andy.zhai
 */
#include <stdio.h>

#include "rtthread.h"

#include "Commu.h"
#include "CommuRoute.h"
#include "CommuApi.h"

//#define COMMU_DEBUG

#define COMMU_MESSAGE_LEN 10
static rt_mq_t commu_queue = RT_NULL;

void SendMessageToCommu(uint8_t *data, uint32_t len)
{
    message_t msg;
    msg.data = data;
    msg.len = len;
    // 将消息发送到COMMU队列中
    if (rt_mq_send(commu_queue, &msg, sizeof(msg)) != RT_EOK) {
        rt_kprintf("[Commu]:queue send fail\n");
    }
}

void CommuTask(void *pvParameters)
{
    while (1) {
        message_t msg;
        // 等待接收消息
        if (rt_mq_recv(commu_queue, &msg, sizeof(msg), RT_WAITING_FOREVER) == RT_EOK) {
#ifdef COMMU_DEBUG
            rt_kprintf("[Commu]:recv %ld bytes\n", msg.len);
#endif
            RouteData(msg.data, msg.len);
        }
    }
}

int CommuInit(void)
{
    commu_queue = rt_mq_create("commu queue", sizeof(message_t), COMMU_MESSAGE_LEN, RT_IPC_FLAG_FIFO);
    if (commu_queue == RT_NULL) {
        rt_kprintf("[Commu]:queue create fail\n");
    }

    rt_thread_t thread = rt_thread_create(
        "Commu",          // 任务名称
        CommuTask,       // 任务入口函数
        NULL,          // 传递给任务的参数
        512,             // 栈大小（单位：字节）
        5,                // 优先级（数值越小，优先级越高）
        10                // 时间片（单位：OS Tick）
    );

    if (thread != RT_NULL) {
        rt_thread_startup(thread); // 启动任务
    } else {
        rt_kprintf("[Commu]:task create fail\n");
    }

    rt_kprintf("[Commu]:task init finish\n");
    return 0;
}
INIT_COMPONENT_EXPORT(CommuInit);
